'use strict';

/////////////////////////////////////////////////
/////////////////////////////////////////////////
// BANKIST APP

/////////////////////////////////////////////////
// Data

// DIFFERENT DATA! Contains movement dates, currency and locale

const account1 = {
  owner: 'Jonas Schmedtmann',
  movements: [200, 455.23, -306.5, 25000, -642.21, -133.9, 79.97, 1300],
  interestRate: 1.2, // %
  pin: 1111,

  movementsDates: [
    '2019-11-18T21:31:17.178Z',
    '2019-12-23T07:42:02.383Z',
    '2020-01-28T09:15:04.904Z',
    '2020-04-01T10:17:24.185Z',
    '2020-05-08T14:11:59.604Z',
    '2020-05-27T17:01:17.194Z',
    '2020-07-11T23:36:17.929Z',
    '2024-08-14T10:51:36.790Z',
  ],
  currency: 'EUR',
  locale: 'pt-PT', // de-DE
};

const account2 = {
  owner: 'Jessica Davis',
  movements: [5000, 3400, -150, -790, -3210, -1000, 8500, -30],
  interestRate: 1.5,
  pin: 2222,

  movementsDates: [
    '2019-11-01T13:15:33.035Z',
    '2019-11-30T09:48:16.867Z',
    '2019-12-25T06:04:23.907Z',
    '2020-01-25T14:18:46.235Z',
    '2020-02-05T16:33:06.386Z',
    '2020-04-10T14:43:26.374Z',
    '2020-06-25T18:49:59.371Z',
    '2024-08-13T12:01:20.894Z',
  ],
  currency: 'USD',
  locale: 'en-US',
};

const accounts = [account1, account2];

/////////////////////////////////////////////////
// Elements
const labelWelcome = document.querySelector('.welcome');
const labelDate = document.querySelector('.date');
const labelBalance = document.querySelector('.balance__value');
const labelSumIn = document.querySelector('.summary__value--in');
const labelSumOut = document.querySelector('.summary__value--out');
const labelSumInterest = document.querySelector('.summary__value--interest');
const labelTimer = document.querySelector('.timer');

const containerApp = document.querySelector('.app');
const containerMovements = document.querySelector('.movements');

const btnLogin = document.querySelector('.login__btn');
const btnTransfer = document.querySelector('.form__btn--transfer');
const btnLoan = document.querySelector('.form__btn--loan');
const btnClose = document.querySelector('.form__btn--close');
const btnSort = document.querySelector('.btn--sort');

const inputLoginUsername = document.querySelector('.login__input--user');
const inputLoginPin = document.querySelector('.login__input--pin');
const inputTransferTo = document.querySelector('.form__input--to');
const inputTransferAmount = document.querySelector('.form__input--amount');
const inputLoanAmount = document.querySelector('.form__input--loan-amount');
const inputCloseUsername = document.querySelector('.form__input--user');
const inputClosePin = document.querySelector('.form__input--pin');

/////////////////////////////////////////////////
// Functions\

const calcDaysPassed = (date1, date2) =>
  Math.floor(Math.abs(date2 - date1) / (1000 * 60 * 60 * 24));

const formatMovementDate = function(date,locale){
    const daysPassed = calcDaysPassed(new Date(),date);
    console.log(daysPassed);
    if(daysPassed === 0){
      return 'Today';
    }
    if(daysPassed ===1){
      return 'Yesterday';
    }
    if(daysPassed<=7){
      return `${daysPassed} days ago `;
    }else{
      // const day = `${date.getDate()}`.padStart(2,0);
      // const month = `${date.getMonth()+1}`.padStart(2,0);
      // const year = date.getFullYear();
      // return `${day}/${month}/${year}`;
      return new Intl.DateTimeFormat(locale).format(date);

    }

}

const formatCur = function(value,locale,currency){
  const formattedMov = new Intl.NumberFormat(locale,{
    style:'currency',
    currency:currency,
  }).format(value);
  return formattedMov;
}

const displayMovements = function (acc, sort = false) {
  containerMovements.innerHTML = '';

  const movs = sort ? acc.movements.slice().sort((a, b) => a - b) : acc.movements;

  movs.forEach(function (mov, i) {
    const type = mov > 0 ? 'deposit' : 'withdrawal';
    const date = new Date(acc.movementsDates[i]);
    const displayDate =formatMovementDate(date,acc.locale);
    const formattedMov = formatCur(mov,acc.locale,acc.currency);
   
    const html = `
      <div class="movements__row">
        <div class="movements__type movements__type--${type}">${
      i + 1
    } ${type}</div>
    <div class="movements__date">${displayDate}</div>
        <div class="movements__value">${formattedMov}</div>
      </div>
    `;

    containerMovements.insertAdjacentHTML('afterbegin', html);
  });
};

const calcDisplayBalance = function (acc) {
  acc.balance = acc.movements.reduce((acc, mov) => acc + mov, 0);
  const formattedMov = formatCur(acc.balance.toFixed(2),acc.locale,acc.currency);
  labelBalance.textContent = formattedMov;
};

const calcDisplaySummary = function (acc) {
  const incomes = acc.movements
    .filter(mov => mov > 0)
    .reduce((acc, mov) => acc + mov, 0);
    const formattedIncome = formatCur(incomes.toFixed(2),acc.locale,acc.currency);
    labelSumIn.textContent = formattedIncome;

  const out = acc.movements
    .filter(mov => mov < 0)
    .reduce((acc, mov) => acc + mov, 0);
  const formattedOut = formatCur(out.toFixed(2),acc.locale,acc.currency);
  labelSumOut.textContent = formattedOut;

  const interest = acc.movements
    .filter(mov => mov > 0)
    .map(deposit => (deposit * acc.interestRate) / 100)
    .filter((int, i, arr) => {
      // console.log(arr);
      return int >= 1;
    })
    .reduce((acc, int) => acc + int, 0);
  const formattedInterest = formatCur(interest.toFixed(2),acc.locale,acc.currency);
  labelSumInterest.textContent = formattedInterest;
};

const createUsernames = function (accs) {
  accs.forEach(function (acc) {
    acc.username = acc.owner
      .toLowerCase()
      .split(' ')
      .map(name => name[0])
      .join('');
  });
};
createUsernames(accounts);
//一定的时间后会自动注销用户
const startLogOutTimer = function(){
  let time =10;
  //每隔1s就调用时钟
  const timer = setInterval(function(){
    const min = Math.trunc(time/60);
    const sec = `${time%60}`.padStart(2,0);
    //每次显示剩余的时间
    labelTimer.textContent = `${min}:${sec}`;
   
    if(time === 0){
      clearInterval(timer);
      labelWelcome.textContent = 'Log in to get start';
      containerApp.style.opacity = 0;
    }
     //减少time
     time--;

  },1000)
}

const updateUI = function (acc) {
  // Display movements
  displayMovements(acc);

  // Display balance
  calcDisplayBalance(acc);

  // Display summary
  calcDisplaySummary(acc);
};

///////////////////////////////////////
// Event handlers
let currentAccount;
//模拟登录，方便做测试
currentAccount = account1;

updateUI(currentAccount);
containerApp.style.opacity = 100;

//按用户地区显示日期
const nowTime = new Date();
const options = {
  hour:'numeric',
  minute:'numeric',
  day:'numeric',
  month:'long',
  year:'numeric',
  weekday:'long'
}
labelDate.textContent = new Intl.DateTimeFormat(currentAccount.locale,options).format(nowTime);

const day = `${nowTime.getDate()}`.padStart(2,0);
const month = `${nowTime.getMonth()+1}`.padStart(2,0);
const year = nowTime.getFullYear();
const hour = `${nowTime.getHours()}`.padStart(2,0);
const min = `${nowTime.getMinutes()}`.padStart(2,0);
//labelDate.textContent = `${day}/${month}/${year},${hour}:${min}`;

btnLogin.addEventListener('click', function (e) {
  // Prevent form from submitting
  e.preventDefault();

  currentAccount = accounts.find(
    acc => acc.username === inputLoginUsername.value
  );
  console.log(currentAccount);

  if (currentAccount?.pin === Number(inputLoginPin.value)) {
    // Display UI and message
    labelWelcome.textContent = `Welcome back, ${
      currentAccount.owner.split(' ')[0]
    }`;
    containerApp.style.opacity = 100;

    // Clear input fields
    inputLoginUsername.value = inputLoginPin.value = '';
    inputLoginPin.blur();

    startLogOutTimer();

    // Update UI
    updateUI(currentAccount);
  }
});

btnTransfer.addEventListener('click', function (e) {
  e.preventDefault();
  const amount = Number(inputTransferAmount.value);
  const receiverAcc = accounts.find(
    acc => acc.username === inputTransferTo.value
  );
  inputTransferAmount.value = inputTransferTo.value = '';

  if (
    amount > 0 &&
    receiverAcc &&
    currentAccount.balance >= amount &&
    receiverAcc?.username !== currentAccount.username
  ) {
    // Doing the transfer
    currentAccount.movements.push(-amount);
    receiverAcc.movements.push(amount);

    // Add date 
    currentAccount.movementsDates.push(Date.now());
    receiverAcc.movementsDates.push(Date.now());
  
    // Update UI
    updateUI(currentAccount);
  }
});

btnLoan.addEventListener('click', function (e) {
  e.preventDefault();

  const amount = Math.floor(inputLoanAmount.value);

  if (amount > 0 && currentAccount.movements.some(mov => mov >= amount * 0.1)) {
    // Add movement
    currentAccount.movements.push(amount);

    // Add date 
    currentAccount.movementsDates.push(Date.now());

    // Update UI
    updateUI(currentAccount);
  }
  inputLoanAmount.value = '';
});

btnClose.addEventListener('click', function (e) {
  e.preventDefault();

  if (
    inputCloseUsername.value === currentAccount.username &&
    Number(inputClosePin.value) === currentAccount.pin
  ) {
    const index = accounts.findIndex(
      acc => acc.username === currentAccount.username
    );
    console.log(index);
    // .indexOf(23)

    // Delete account
    accounts.splice(index, 1);

    // Hide UI
    containerApp.style.opacity = 0;
  }

  inputCloseUsername.value = inputClosePin.value = '';
});

let sorted = false;
btnSort.addEventListener('click', function (e) {
  e.preventDefault();
  displayMovements(currentAccount, !sorted);
  sorted = !sorted;
});

/////////////////////////////////////////////////
/////////////////////////////////////////////////
// LECTURES

labelBalance.addEventListener('click',function(){
  [...document.querySelectorAll('.movements__row')].forEach((row,i)=>{
    if(i%2==0){
      row.style.backgroundColor = 'orangered'
    }
  })
})

const now = new Date();
console.log(now);
console.log(new Date('Aug 14 2024'));
console.log(new Date(2024, 7 ,14 ,11, 32 ,25));//给出数字也能给时间，年月日时分秒
console.log(new Date(0));//最开始的时间Thu Jan 01 1970 08:00:00 GMT+0800 (中国标准时间)
console.log(now.getFullYear());//得到时间的年月日
console.log(now.toISOString());//得到ISO类型的日期2024-08-14T03:35:30.222Z

//可以带一个回调函数，实现在指定的时间后执行某个操作
setTimeout(()=>{
  console.log('hihihihi')
},3000);